package com.mytx.mapper;

import com.mytx.pojo.LatLng;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LocationTypeHandler extends BaseTypeHandler<LatLng> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LatLng parameter, JdbcType jdbcType) throws SQLException {
        StringBuilder builder = new StringBuilder("[")
                .append(parameter.getLat())
                .append(",")
                .append(parameter.getLon())
                .append("]");

        ps.setString(i, builder.toString());
    }

    @Override
    public LatLng getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (rs.getString(columnName) != null) {
        String[] latLng = rs.getString(columnName).replace("[", "").replace("]", "").split(",");
        return new LatLng(Double.valueOf(latLng[0]), Double.valueOf(latLng[1]));
        }
        return null;
    }

    @Override
    public LatLng getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if (rs.getString(columnIndex) != null) {
            String[] latLng = rs.getString(columnIndex).replace("[", "").replace("]", "").split(",");
            return new LatLng(Double.valueOf(latLng[0]), Double.valueOf(latLng[1]));
        }
        return null;
    }

    @Override
    public LatLng getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (cs.getString(columnIndex) != null) {
            String[] latLng = cs.getString(columnIndex).replace("[", "").replace("]", "").split(",");
            return new LatLng(Double.valueOf(latLng[0]), Double.valueOf(latLng[1]));
        }
        return null;
    }
}
